package cn.layfolk.seckill.mq.listener;

import cn.hutool.json.JSONUtil;
import cn.layfolk.daimao.consts.MQConstans;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import cn.layfolk.seckill.mq.msg.CreateOrderMessage;
import cn.layfolk.seckill.mq.msg.DelayOrderMessage;
import cn.layfolk.seckill.service.TOrderInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;



@RocketMQMessageListener(
        topic = MQConstans.SECKILL_ORDER_TOPIC,
        consumerGroup = MQConstans.CREATE_SECKILL_ORDER_GROUP,
        selectorExpression = MQConstans.CREATE_SECKILL_ORDER_TAG
)
@Component
public class CreateSeckillOrderMQListener implements RocketMQListener<CreateOrderMessage> {

    private final Logger log = LoggerFactory.getLogger("CREATE_SECKILL_ORDER_MQ_LISTENER");
    @Autowired
    private TOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(CreateOrderMessage message) {
        log.info("收到创建订单消息：{}", JSONUtil.toJsonStr(message));
        //直接调用秒杀服务进行创建秒杀订单
        try {
           String orderNo =  orderInfoService.doSeckill(message.getSeckillId(),message.getUserId());
           // 订单创建成功，发送订单创建成功消息{code:0,msg:"",data:{}}
            Map<String,Object> data = new HashMap<>();
            data.put("orderNo", orderNo);
            data.put("uuid", message.getUuid());
            rocketMQTemplate.syncSend(MQConstans.SECKILL_ORDER_SUCCESS_DEST, ResponseVo.ok(data));
            // 发送一个延迟消息，在30分钟后检查订单是否已支付
            DelayOrderMessage delayOrderMessage = new DelayOrderMessage(orderNo, message.getSeckillId());
            GenericMessage<DelayOrderMessage> msg = new GenericMessage<>(delayOrderMessage);
            //delayLevel= 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
            rocketMQTemplate.syncSend(MQConstans.DELAY_ORDER_DEST,msg,3000,16);
        } catch (Exception e) {
            // 创建失败的相关逻辑
            log.error("订单创建失败", e);
            // 调用service方法，完成库存回补&清除本地标记
            orderInfoService.handleCreateOrderFailed(message.getSeckillId());
            // 发送一个订单创建失败的结果消息
            rocketMQTemplate.syncSend(MQConstans.SECKILL_ORDER_FAILED_DEST, message.getUuid());
        }
    }
}
